package com.cl.activity;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import net.tsz.afinal.FinalHttp;
import net.tsz.afinal.http.AjaxCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.cl.safe.R;
import com.cl.utils.StreamTools;

public class SplashActivity extends Activity {
	protected static final String TAG = "SplashActivity";
	protected static final int ENTER_HOME = 0;
	protected static final int SHOW_UPDATE_DIALOG = 1;
	protected static final int URL_ERROR = 2;
	protected static final int NETWORK_ERROR = 3;
	protected static final int JSON_ERROR = 4;
	private TextView tv_splash_version;
	private TextView tv_splash_download;
	private String currentVersion;
	private String updateinfo;
	private String apkurl;
	private SharedPreferences sp;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		tv_splash_version = (TextView) findViewById(R.id.tv_splash_version);
		tv_splash_download = (TextView) findViewById(R.id.tv_splash_download);
		sp = getSharedPreferences("config", MODE_PRIVATE);
		// 设置app版本号
		currentVersion = getCurrentVersion();
		tv_splash_version.setText("版本：" + currentVersion);
		// path 把address.db这个数据库拷贝到data/data/《包名》/files/address.db
		copyDB("address.db");
		copyDB("antivirus.db");
		boolean isUpdate = sp.getBoolean("isUpdate", false);
		if(isUpdate) {
			checkUpdate();
		}else {
			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					enterHome();
				}
			}, 2000);
		}
		
	}

	private void copyDB(String filename) {
		File file = new File(getFilesDir(),filename);
		if(file.exists() && file.length() > 0) {
			Log.e(TAG, "数据库文件只需要拷贝一下，如果拷贝了，不需要重新拷贝了");
		}else {
			try {
				//数据库文件只需要拷贝一下，如果拷贝了，不需要重新拷贝了。
				InputStream is = getAssets().open(filename);
				BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file));
				byte[] bys = new byte[1024];
				int length = 0;
				while((length = is.read(bys)) != -1) {
					bos.write(bys, 0, length);
				}
				is.close();
				bos.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	}

	/**
	 * 获取当前app的版本
	 */
	private String getCurrentVersion() {
		PackageManager pm = getPackageManager();
		try {
			PackageInfo packageInfo = pm.getPackageInfo("com.itheima.safe", 0);
			String version = packageInfo.versionName;
			return version;
		} catch (NameNotFoundException e) {
			e.printStackTrace();
			return "";
		}
	}

	/**
	 * 检查是否有新版本，如果有就升级
	 */
	private void checkUpdate() {
		new Thread() {
			public void run() {
				Message msg = Message.obtain();
				long startTime = System.currentTimeMillis();
				try {
					URL url = new URL(getString(R.string.serverurl));
					Log.i(TAG, "联网了:" + getString(R.string.serverurl));
					// 联网
					HttpURLConnection conn = (HttpURLConnection) url
							.openConnection();
					conn.setRequestMethod("GET");
					conn.setConnectTimeout(4000);
					int code = conn.getResponseCode();
					if (code == 200) {
						//联网成功了
						InputStream is = conn.getInputStream();
						String result = StreamTools.readFromStream(is);
						Log.i(TAG, "联网成功了" + result);
						JSONObject obj = new JSONObject(result);
						//JSON解析
						apkurl = (String) obj.get("apkurl");
						updateinfo = (String) obj.get("info");
						Log.i(TAG, updateinfo);
						String newVersion = (String) obj.get("version");
						if(currentVersion.equals(newVersion)) {//版本一致，进入主页
							msg.what = ENTER_HOME;
						}else {
							//有新版本，显示更新提示对话框
							msg.what = SHOW_UPDATE_DIALOG;
						}
					} else {
						msg.what = ENTER_HOME;
					}
				} catch (MalformedURLException e) {
					Log.i(TAG, "url出错了 what is up");
					msg.what = URL_ERROR;
					e.printStackTrace();
				} catch (IOException e) {
					msg.what = NETWORK_ERROR;
					e.printStackTrace();
				} catch (JSONException e) {
					msg.what = JSON_ERROR;
					e.printStackTrace();
				}finally {
					long endTime = System.currentTimeMillis();
					long dTime = endTime - startTime;
					if(dTime < 2000) {
						try {
							Thread.sleep(2000 - dTime);
						} catch (InterruptedException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
					handler.sendMessage(msg);
				}
			};
		}.start();
	}

	/**
	 * 进入主界面
	 */
	protected void enterHome() {
		Intent intent = new Intent(this,HomeActivity.class);
		startActivity(intent);
		// 关闭当前页面
		finish();
	}
	
	/**
	 * 弹出升级对话框
	 */
	protected void showUpdateDialog() {
		AlertDialog.Builder builder = new Builder(SplashActivity.this);
		builder.setTitle("更新提示");
		builder.setMessage(updateinfo);
		builder.setOnCancelListener(new OnCancelListener() {
			@Override
			public void onCancel(DialogInterface dialog) {
				dialog.dismiss();
				enterHome();
			}
		});
		builder.setPositiveButton("确定", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				Log.i(TAG, "点击了更新");
				// 下载APK，并且替换安装
				if (Environment.getExternalStorageState().equals(
						Environment.MEDIA_MOUNTED)) {
					// sdcard存在
					// afinal
					FinalHttp fianlHttp = new FinalHttp();
					fianlHttp.download(apkurl, Environment.getExternalStorageDirectory()
							.getAbsolutePath()+"/mobilesafe2.0.apk",
							new AjaxCallBack<File>() {

								@Override
								public void onFailure(Throwable t, int errorNo,
										String strMsg) {
									t.printStackTrace();
									Toast.makeText(getApplicationContext(), "下载失败", 0).show();
									super.onFailure(t, errorNo, strMsg);
								}

								@Override
								public void onLoading(long count, long current) {
									int process = (int) (current * 100 / count);
									tv_splash_download.setText("已下载了: "+process+"%");
									super.onLoading(count, current);
								}

								@Override
								public void onSuccess(File t) {
									installAPK(t);
									super.onSuccess(t);
								}

								/**
								 * 安装APK
								 * @param t
								 */
								private void installAPK(File t) {
								  Intent intent = new Intent();
								  intent.setAction("android.intent.action.VIEW");
								  intent.addCategory("android.intent.category.DEFAULT");
								  intent.setDataAndType(Uri.fromFile(t), "application/vnd.android.package-archive");
								  
								  startActivity(intent);
								}
							});
				}else {
					Toast.makeText(SplashActivity.this, "sd不存在，请安装后再试", 0).show();
				}
			}
		});
		builder.setNegativeButton("下次再说", new OnClickListener() {
			@Override
			public void onClick(DialogInterface dialog, int which) {
				dialog.dismiss();
				enterHome();
			}
		});
		builder.show();
	}
	private Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			super.handleMessage(msg);
			switch (msg.what) {
			case ENTER_HOME:
				enterHome();
				break;
			case SHOW_UPDATE_DIALOG:
				showUpdateDialog();
				break;
			case URL_ERROR:
				Toast.makeText(getApplicationContext(), "网络路径异常", 0).show();
				enterHome();
				break;
			case NETWORK_ERROR:
				Toast.makeText(getApplicationContext(), "网络异常", 0).show();
				enterHome();
				break;
			case JSON_ERROR:
				Toast.makeText(getApplicationContext(), "json异常", 0).show();
				enterHome();
				break;
			}
		}
		
	};
}
